package com.example.demo.leetcode.classics150;

import java.util.HashMap;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _72从前序与中序遍历序列构造二叉树
 * @description
 * @date 2023/07/31 16:13
 * <p>
 * ******************************************************
 */
public class _72从前序与中序遍历序列构造二叉树 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> valueToIndex = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            valueToIndex.put(inorder[i], i);
        }

        return buildTree(preorder, 0, preorder.length - 1,
                inorder, 0, inorder.length - 1, valueToIndex);
    }

    private TreeNode buildTree(int[] preorder, int preStart, int preEnd,
                               int[] inorder, int inStart, int inEnd, Map<Integer, Integer> valueToIndex) {
        if (preEnd < preStart) {
            return null;
        }
        int rootValue = preorder[preStart];
        TreeNode root = new TreeNode(rootValue);
        int leftSize = valueToIndex.get(rootValue) - inStart;
        TreeNode left = buildTree(preorder, preStart + 1, preStart + leftSize, inorder, inStart, inStart + leftSize - 1, valueToIndex);
        TreeNode right = buildTree(preorder, preStart + leftSize + 1, preEnd, inorder, inStart + leftSize + 1, inEnd, valueToIndex);
        root.left = left;
        root.right = right;
        return root;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
